from rest_framework.exceptions import ValidationError
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated
from rest_framework import status
from .models import Photo, Album
from .serializers import PhotoSerializer, AlbumSerializer
from django.shortcuts import get_object_or_404

from .pagination import StandardResultsSetPagination  # 新建 pagination.py 存分页类


class PhotoListCreateView(APIView):
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get(self, request):
        photos = Photo.objects.all().order_by('-uploaded_at')

        # 如果传参 ?user_only=true，则只返回当前用户上传的
        if request.query_params.get('user_only') == 'true' and request.user.is_authenticated:
            photos = photos.filter(uploaded_by=request.user)

        paginator = StandardResultsSetPagination()
        result_page = paginator.paginate_queryset(photos, request)
        serializer = PhotoSerializer(result_page, many=True)
        return paginator.get_paginated_response(serializer.data)

    def post(self, request):
        serializer = PhotoSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class PhotoDetailView(APIView):
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get_object(self, pk):
        return get_object_or_404(Photo, pk=pk)

    def get(self, request, pk):
        photo = self.get_object(pk)
        serializer = PhotoSerializer(photo)
        return Response(serializer.data)

    def put(self, request, pk):
        photo = self.get_object(pk)
        if photo.uploaded_by != request.user:
            return Response({"detail": "无权修改该图片"}, status=status.HTTP_403_FORBIDDEN)

        serializer = PhotoSerializer(photo, data=request.data, partial=True, context={'request': request})
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        photo = self.get_object(pk)
        if photo.uploaded_by != request.user:
            return Response({"detail": "无权删除该图片"}, status=status.HTTP_403_FORBIDDEN)

        photo.delete()
        return Response({"detail": "删除成功"}, status=status.HTTP_204_NO_CONTENT)



# 相册
# views.py
class AlbumListCreateView(APIView):
    '''创建相册'''
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get(self, request):
        albums = Album.objects.all().order_by('-created_at')
        serializer = AlbumSerializer(albums, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = AlbumSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(owner=request.user)
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)



class PhotoMultiUploadView(APIView):
    '''多图上传'''
    permission_classes = [IsAuthenticated]

    def post(self, request, album_id):
        album = get_object_or_404(Album, id=album_id, owner=request.user)

        files = request.FILES.getlist('images')
        titles = request.data.getlist('titles')  # 可选，标题列表

        photos = []
        for i, file in enumerate(files):
            photo = Photo(
                image=file,
                title=titles[i] if i < len(titles) else '',
                album=album,
                uploaded_by=request.user
            )
            try:
                photo.full_clean()  # 调用验证器（如图片大小）
                photo.save()
                photos.append(photo)
            except ValidationError as e:
                return Response({'detail': str(e)}, status=400)

        serializer = PhotoSerializer(photos, many=True)
        return Response(serializer.data, status=201)
